from tornado import gen
from base.BaseHandler import AuthHandler
from base.Models import Users

img_type = ["jpg", "png", "jpeg", "JPG", "PNG", "JPEG"]


class ChangeHeadImgHandler(AuthHandler):
    @gen.coroutine
    def post(self):
        # 更改头像
        result = self.result()
        try:
            file = self.data_not_null(self.request.files, "file", "请上传文件！")
            file_name = file[0]["filename"]
            print(file_name)
            file_type = file_name.split(".")[1]
            if file_type not in img_type:
                self.data_except("请上传图片！")

            user_verify = self.session.query(Users).filter_by(id=self.user_id, is_delete=0).first()
            if not user_verify:
                self.data_except("账户不存在！")

            # 保存图片
            file_path, online_path = self.get_file_path("head_img", file_type=file_type)
            with open(file_path, "wb")as f:
                f.write(file[0]["body"])

            user_verify.head_img = online_path
            self.record_user_operation(user_verify.id, user_verify.nick_name, todo="用户更改头像！")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "头像更改成功！"
            self.logger.info(f"用户-{user_verify.nick_name}-更改头像")
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)


